package com.atguigu.datastream.day08;

import com.atguigu.datastream.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * ClassName: Flink01_KeyedState_ValueState_TTL
 * Package: com.atguigu.day08
 * Description:
 *
 * @Author ChenJun
 * @Create 2023/4/15 16:31
 * @Version 1.0
 */
public class Flink01_KeyedState_ValueState_TTL {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3.将数据转为JavaBean，为了方便提取数据
        SingleOutputStreamOperator<WaterSensor> waterSensorDStream = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });

        //4.将相同id的数据聚合到一块
        KeyedStream<WaterSensor, Tuple> keyedStream = waterSensorDStream.keyBy("id");

        //TODO 5.需求：检测传感器的水位线值，如果连续的两个水位线差值超过10，就输出报警
        keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {

            //TODO 1.定义状态
            private ValueState<Integer> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                //TODO 设置状态的存活时间
                ValueStateDescriptor<Integer> state = new ValueStateDescriptor<>("valueState", Types.INT);
                state.enableTimeToLive(new StateTtlConfig.Builder(Time.seconds(5))
                        .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)
                        .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                        .build());

                //TODO 2.初始化状态


                valueState = getRuntimeContext().getState(state);
//                valueState = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("valueState", Types.INT,0));
            }

            @Override
            public void processElement(WaterSensor value, KeyedProcessFunction<Tuple, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                //TODO 3.使用状态
                //a.从状态中获取上一次的水位值
                int lastVc = valueState.value() == null ? 0 : valueState.value();

               /* Integer lastVc;
                if (valueState.value()==null){
                    lastVc = 0;
                }else {
                    lastVc = valueState.value();
                }*/


                System.out.println(lastVc);
                //b.判断两个水位值差值是否超过10
                if (Math.abs(value.getVc() - lastVc) > 10) {
                    out.collect("水位超过10，报警！！！！！");
                }

                //c.再将当前水位更新到状态中，便于下一次水位来的时候做判断
                valueState.update(value.getVc());
            }
        }).print();

        env.execute();


    }

}
